<template>
  <!-- 企业基本信息 -->
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="180px">
      <el-row>
        <el-col :span="24">
          <el-button style="margin: 14px 0px; float: right" type="primary" @click="submitForm">保存</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="机构名称" prop="orgName">
            <el-input v-model="form.orgName" placeholder="请输入机构名称" @input="input" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="统一信用代码" prop="orgCode">
            <el-input v-model="form.orgCode" placeholder="请输入统一信用代码" @input="input" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="企业类型" prop="businessType">
            <el-select v-model="form.businessType" placeholder="请选择企业类型">
              <el-option
                v-for="dict in dict.type.bhxq_business_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="运输类型" prop="transportType">
            <el-select v-model="form.transportType" placeholder="请选择运输类型">
              <el-option
                v-for="dict in dict.type.bhxq_enterprise_transport_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="注册资本" prop="registeredCapital">
<!--            <el-input v-model="form.registeredCapital" placeholder="请输入注册资本" />-->
            <el-input class="delInput" v-model.number="form.registeredCapital" type="number" placeholder="请输入注册资本"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="企业法人名称" prop="legalPerson">
            <el-input v-model="form.legalPerson" placeholder="请输入企业法人名称" />
          </el-form-item>
        </el-col>

      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="法人电话" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入法人电话" maxlength="11" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="企业联系电话（座机）" prop="telephone">
            <el-input v-model="form.telephone" placeholder="请输入企业联系电话（座机）" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="企业联系人" prop="linkman">
            <el-input v-model="form.linkman" placeholder="请输入企业联系人" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="联系人电话" prop="linkphone">
            <el-input v-model="form.linkphone" placeholder="请输入联系人电话" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="登记状态" prop="registerStatus">
            <el-select v-model="form.registerStatus" placeholder="请选择登记状态">
              <el-option
                v-for="dict in dict.type.bhxq_enterprise_register_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="营运状态" prop="tradeStatus">
            <el-select v-model="form.tradeStatus" placeholder="请选择营运状态">
              <el-option
                v-for="dict in dict.type.bhxq_enterprise_trade_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="营业期限" prop="tradeDeadline">
            <el-date-picker
              v-model="form.tradeDeadline"
              type="date"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="执照发证机关" prop="licenseIssueOrg">
            <el-input v-model="form.licenseIssueOrg" placeholder="请输入执照发证机关" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="纳税人识别号" prop="taxpayerNum">
            <el-input v-model="form.taxpayerNum" placeholder="请输入纳税人识别号" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="成立日期" prop="establishedDate">
            <el-date-picker
              v-model="form.establishedDate"
              type="date"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属辖区" prop="area">
            <el-select v-model="form.area" placeholder="请选择所属辖区">
              <el-option
                v-for="dict in dict.type.bhxq_area_scope"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属街道" prop="street">
            <el-input v-model="form.street" placeholder="请输入所属街道" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="注册地址：" prop="registerAddr">
            <el-autocomplete
              v-model="form.registerAddr"
              :fetch-suggestions="querySearchAsync"
              :trigger-on-focus="false"
              clearable
              placeholder="请先搜索地址"
              style="width: 100%"
              @select="handleSelect"
            >
              <template slot-scope="{ item }">
                <i class="el-icon-search fl mgr10" />
                <div style="overflow: hidden">
                  <div class="title">{{ item.title }}</div>
                  <span class="address ellipsis">{{ item.address }}</span>
                </div>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8" :offset="1">
          <el-form-item label="经度" prop="registerAddrLong">
            <el-input v-model="form.registerAddrLong" placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="纬度" prop="registerAddrLat">
            <el-input v-model="form.registerAddrLat" placeholder="" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="地图定位：">
            <div id="map-container" style="width: 100%; height: 300px" />
          </el-form-item>
        </el-col>
      </el-row>
      <!--      <el-row>-->
      <!--        <el-col :span="24">-->
      <!--          <el-form-item label="办公地址" prop="workAddr">-->
      <!--            <el-input v-model="form.workAddr" placeholder="请输入办公地址" />-->
      <!--          </el-form-item>-->
      <!--        </el-col>-->
      <!--      </el-row>-->

      <el-row>
        <el-col :span="24">
          <el-form-item label="办公地址：" prop="workAddr">
            <el-autocomplete
              v-model="form.workAddr"
              :fetch-suggestions="querySearchAsync2"
              :trigger-on-focus="false"
              clearable
              placeholder="请先搜索地址"
              style="width: 100%"
              @select="handleSelect2"
            >
              <template slot-scope="{ item }">
                <i class="el-icon-search fl mgr10" />
                <div style="overflow: hidden">
                  <div class="title">{{ item.title }}</div>
                  <span class="address ellipsis">{{ item.address }}</span>
                </div>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8" :offset="1">
          <el-form-item label="经度" prop="workAddrLong">
            <el-input v-model="form.workAddrLong" placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="纬度" prop="workAddrLat">
            <el-input v-model="form.workAddrLat" placeholder="" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="地图定位：">
            <div id="map-container2" style="width: 100%; height: 300px" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="经营范围" prop="businessScope">
            <el-input v-model="form.businessScope" placeholder="请输入经营范围" />
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
  </div>
</template>

<script>
// 引入第三方工具包
import loadBMap from '@/api/bhxq/loadBMap.js'
import { getCompany, saveCompany } from '@/api/informationReport'
export default {
  name: 'Index',
  dicts: ['bhxq_business_type', 'bhxq_enterprise_transport_type', 'bhxq_enterprise_register_status', 'bhxq_area_scope', 'bhxq_enterprise_trade_status'],
  beforeRouteLeave(to, from, next) {
    // 在这里进行路由跳转控制 当公司id为空时 完善公司信息后才能跳转到其他页面
    if (this.$store.state.user.user.enterpriseId === null) {
      if (this.$message.error('请完善企业基本信息')) {
        // next()
      } else {
        next(false)
      }
    } else {
      next()
    }
  },
  data() {
    return {
      companyId: this.$store.state.user.user.enterpriseId, // 公司id
      // 登记状态字典
      registStaList: [],
      // 营运状态字典
      serCondiList: [],
      // 机构层级字典
      instituHie: [],
      // 所属辖区字典
      areaJurisdictionn: [],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企业信息表格数据
      tableList: [],
      // 弹出层标题
      title: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // businessType: '1',
        // establishedDate:null,
        orgName: null,
        orgCode: null
      },
      // // 表单参数
      form: {
        // businessType: '1',
        id: this.$store.state.user.user.enterpriseId,
        registerAddr: null,
        workAddr: null
      },
      // 表单校验
      rules: {
        transportType: [
          { required: true, message: '运输类型不能为空', trigger: 'change' }
        ],
        orgName: [
          { required: true, message: '机构名称不能为空', trigger: 'blur' }
        ],
        orgCode: [
          { required: true, message: '统一信用代码不能为空', trigger: 'blur' }
        ],
        businessType: [
          { required: true, message: '企业类型不能为空', trigger: 'change' }
        ],
        registeredCapital: [
          { required: true, message: '注册资本不能为空', trigger: 'blur' }
        ],
        legalPerson: [
          { required: true, message: '企业法人名称不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '法人电话不能为空', trigger: 'blur' }
        ],
        // telephone: [
        //   { required: true, message: '企业联系电话（座机）不能为空', trigger: 'blur' }
        // ],
        linkman: [
          { required: true, message: '企业联系人不能为空', trigger: 'blur' }
        ],
        linkphone: [
          { required: true, message: '联系人电话不能为空', trigger: 'blur' }
        ],
        registerStatus: [
          { required: true, message: '登记状态不能为空', trigger: 'change' }
        ],
        tradeStatus: [
          { required: true, message: '营运状态不能为空', trigger: 'change' }
        ],
        tradeDeadline: [
          { required: true, message: '营业期限不能为空', trigger: 'blur' }
        ],
        // licenseIssueOrg: [
        //   { required: true, message: '执照发证机关不能为空', trigger: 'blur' }
        // ],
        // taxpayerNum: [
        //   { required: true, message: '纳税人识别号不能为空', trigger: 'blur' }
        // ],
        establishedDate: [
          { required: true, message: '成立日期不能为空', trigger: 'blur' }
        ],
        area: [
          { required: true, message: '所属辖区不能为空', trigger: 'change' }
        ],
        street: [
          { required: true, message: '所属街道不能为空', trigger: 'blur' }
        ],
        registerAddr: [
          { required: true, message: '注册地不能为空', trigger: 'blur' }
        ],
        registerAddrLong: [
          { required: true, message: '注册地址经度不能为空', trigger: 'blur' }
        ],
        registerAddrLat: [
          { required: true, message: '注册地址纬度不能为空', trigger: 'blur' }
        ],
        workAddr: [
          { required: true, message: '办公地址不能为空', trigger: 'blur' }
        ],
        workAddrLong: [
          { required: true, message: '办公地址经度不能为空', trigger: 'blur' }
        ],
        workAddrLat: [
          { required: true, message: '办公地址纬度不能为空', trigger: 'blur' }
        ]
        // businessScope: [
        //   { required: true, message: '经营范围不能为空', trigger: 'blur' }
        // ]
      },
      // 日期范围
      dateRange: []
    }
  },
  mounted() {
    // console.log('公司id', this.$store.state.user.user)
    const data = {
      enterpriseName: this.$store.state.user.user.enterpriseName,
      orgCode: this.$store.state.user.user.orgCode
    }
    this.form.orgName = data.enterpriseName
    this.form.orgCode = data.orgCode
    console.log('form', this.form)
    this.companyInformation()
    // 页面加载完之后，加载百度地图
    // 加载引入BMap
    loadBMap('https://api.map.baidu.com/api?v=3.0&ak=Fb93ekp4f6yLbTbE2vXjaV3WQm29CIe9')
    // 加载地图
    this.getbaidu()
    this.getbaidu2()
  },
  created() {
  },
  methods: {
    input() {
      this.$forceUpdate()
    },
    /** 获取公司信息 */
    companyInformation() {
      console.log('companyId', this.companyId)
      if (this.companyId !== null) {
        getCompany(this.companyId).then(res => {
          if (res.data !== null) {
            this.form = res.data
          }
        })
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form) {
            saveCompany(this.form).then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess('保存成功')
                if (this.$store.state.user.user.enterpriseId === null) {
                  window.location.reload()
                }
              }
            })
          }
        }
      })
    },
    // 加载地图方法
    getbaidu() {
      this.initMapeq = setInterval(() => {
        if (this.initMap()) {
          clearInterval(this.initMapeq)
        }
      })
    },
    // 百度地图封装方法
    // 初始化地图
    initMap() {
      try {
        var that = this
        // 1、挂载地图
        // 创建地图实例
        this.map = new BMap.Map('map-container')
        // 设置中心经纬度
        var point = new BMap.Point(
          this.form.registerAddrLong || 117.71739451779443,
          this.form.registerAddrLat || 39.009415913825386
        )

        // 3.在创建地图实例后，我们需要对其进行初始化，BMapGL.Map.centerAndZoom()方法要求设置中心点坐标和地图级别。 地图必须经过初始化才可以执行其他操作
        this.map.centerAndZoom(point, 14)
        // 滚轮缩放
        this.map.enableScrollWheelZoom()
        // 3、设置图像标注并绑定拖拽标注结束后事件
        this.mk = new BMap.Marker(point, { enableDragging: true })
        this.map.addOverlay(this.mk)
      } catch (err) {
        return false
      }
      // 4、添加（右上角）平移缩放控件
      this.map.addControl(
        new BMap.NavigationControl({
          anchor: BMAP_ANCHOR_TOP_RIGHT,
          type: BMAP_NAVIGATION_CONTROL_SMALL
        })
      )
      // 7、绑定点击地图任意点事件
      this.map.addEventListener('click', function(e) {
        console.log('点击了', e)
        that.getAddrByPoint(e.point)
      })
      return true
    },
    // 2、逆地址解析函数 根据坐标点获取详细地址  point   百度地图坐标点，必传
    getAddrByPoint(point) {
      var that = this
      var geco = new BMap.Geocoder()
      geco.getLocation(point, function(res) {
        console.log('点击位置的信息:', res)
        that.mk.setPosition(point)
        that.map.panTo(point)
        that.form.registerAddr = res.address
        that.form.registerAddrLong = JSON.stringify(res.point.lng)
        that.form.registerAddrLat = res.point.lat
      })
      console.log('点击后的form表单', this.form)
    },
    // 8-1、地址搜索
    querySearchAsync(str, cb) {
      // 根据状态码
      var options = {
        onSearchComplete: function(res) {
          var s = []
          if (local.getStatus() == BMAP_STATUS_SUCCESS) {
            for (var i = 0; i < res.getCurrentNumPois(); i++) {
              s.push(res.getPoi(i))
            }
            cb(s)
          } else {
            cb(s)
          }
        }
      }
      var local = new BMap.LocalSearch(this.map, options)
      local.search(str)
    },
    // 8-2、选择地址
    handleSelect(item) {
      this.form.registerAddr = item.address + item.title
      // console.log(item);
      this.form.registerAddrLong = item.point.lng
      this.form.registerAddrLat = item.point.lat

      // console.log('lng', item.point.lng)
      // console.log('lat', item.point.lat)
      this.map.clearOverlays()
      this.mk = new BMap.Marker(item.point)
      this.map.addOverlay(this.mk)
      this.map.panTo(item.point)
    },

    // ----

    // 加载地图方法
    getbaidu2() {
      this.initMapeq2 = setInterval(() => {
        if (this.initMap2()) {
          clearInterval(this.initMapeq2)
        }
      })
    },

    // 百度地图封装方法
    // 初始化地图
    initMap2() {
      try {
        console.log('====initMap2===')
        var that = this
        // 1、挂载地图
        // 创建地图实例
        this.map2 = new BMap.Map('map-container2')
        // 设置中心经纬度
        var point = new BMap.Point(
          this.form.workAddrLong || 117.71739451779443,
          this.form.workAddrLat || 39.009415913825386
        )

        // 3.在创建地图实例后，我们需要对其进行初始化，BMapGL.Map.centerAndZoom()方法要求设置中心点坐标和地图级别。 地图必须经过初始化才可以执行其他操作
        this.map2.centerAndZoom(point, 14)
        // 滚轮缩放
        this.map2.enableScrollWheelZoom()
        // 3、设置图像标注并绑定拖拽标注结束后事件
        this.mk2 = new BMap.Marker(point, { enableDragging: true })
        this.map2.addOverlay(this.mk2)
      } catch (err) {
        return false
      }
      // 4、添加（右上角）平移缩放控件
      this.map2.addControl(
        new BMap.NavigationControl({
          anchor: BMAP_ANCHOR_TOP_RIGHT,
          type: BMAP_NAVIGATION_CONTROL_SMALL
        })
      )
      // 7、绑定点击地图任意点事件
      this.map2.addEventListener('click', function(e) {
        console.log('点击了', e)
        that.getAddrByPoint2(e.point)
      })
      return true
    },
    // 2、逆地址解析函数 根据坐标点获取详细地址  point   百度地图坐标点，必传
    getAddrByPoint2(point) {
      var that = this
      var geco = new BMap.Geocoder()
      geco.getLocation(point, function(res) {
        // console.log(res);
        that.mk2.setPosition(point)
        that.map2.panTo(point)
        that.form.workAddr = res.address
        that.form.workAddrLong = res.point.lng
        that.form.workAddrLat = res.point.lat
      })
    },
    // 8-1、地址搜索
    querySearchAsync2(str, cb) {
      // 根据状态码
      var options = {
        onSearchComplete: function(res) {
          var s = []
          if (local.getStatus() == BMAP_STATUS_SUCCESS) {
            for (var i = 0; i < res.getCurrentNumPois(); i++) {
              s.push(res.getPoi(i))
            }
            cb(s)
          } else {
            cb(s)
          }
        }
      }
      var local = new BMap.LocalSearch(this.map2, options)
      local.search(str)
    },
    // 8-2、选择地址
    handleSelect2(item) {
      this.form.workAddr = item.address + item.title
      // console.log(item);
      this.form.workAddrLong = item.point.lng
      this.form.workAddrLat = item.point.lat

      // console.log('lng', item.point.lng)
      // console.log('lat', item.point.lat)
      this.map2.clearOverlays()
      this.mk2 = new BMap.Marker(item.point)
      this.map2.addOverlay(this.mk2)
      this.map2.panTo(item.point)
    }
  }
}
</script>

<style scoped>
.app-container {
  margin: 0px 100px;
}
.el-select {
  display: inline-block;
  position: relative;
  width: 100%;
}
.el-date-editor.el-input, .el-date-editor.el-input__inner {
  width: 100%;
}
/deep/.delInput input::-webkit-outer-spin-button,
/deep/.delInput input::-webkit-inner-spin-button {
  -webkit-appearance: none!important;
}
/deep/.delInput input[type="number"]{
  -moz-appearance: textfield;
}
/deep/.delInput .el-input__inner{
  line-height: 1px !important;
}
</style>
